package com.perye.dokit.workcontroller;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: chenhao
 * \* Date: 2021/7/19
 * \* Time: 20:06
 * \* Description:
 * \
 */


import com.perye.dokit.utils.DateUtils;
import com.perye.dokit.utils.FileChUtil;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

//文件上传
@RestController
//跨域请求
@CrossOrigin
@RequestMapping("/api/upload")
public class UploadController {


    @Value("${file-img.path}")
    private String path;
    @Value("${file-img.visit}")
    private String visit;


    @RequestMapping("/upload")
    public String upload() {
        return "upload";
    }


    @PostMapping("/toImg")
    public ResponseEntity<Object> upload(@RequestParam MultipartFile file) {
        String visitAddress = "";


        // 如果图片为空，显示错误信息
        if ((file.getOriginalFilename().isEmpty())) {

        } else {

            // 获取图片的名字
            String fileNameType = file.getOriginalFilename();

            //获取最后一个.的位置
            int lastIndexOf = fileNameType.lastIndexOf(".");
            //获取文件的后缀名 .jpg
            String suffix = fileNameType.substring(lastIndexOf);

            String fileName = DateUtils.dateTimeNow()  + suffix;
            // 图片存放的文件夹地址
            String filePath = path;
            // 文件夹地址 + 名字 = 图片的路径
            //String fileAddress = filePath + fileName;

            // ngin代理可访问的地址
            visitAddress = visit + fileName;

            try {
                // 图片上传的工具类
                // 参数一：图片的编码格式的字节数组
                // 参数二：图片存放的文件夹地址
                // 参数三：图片的名字
                FileChUtil.uploadFile(file.getBytes(), filePath, fileName);
                // 把图片路径写入数据库
                System.out.println(filePath);
                Thumbnails.of(file.getInputStream()).scale(0.8f).outputFormat("jpg").outputQuality(0.5).toFile(filePath);

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return new ResponseEntity<>(visitAddress, HttpStatus.OK);
    }
}

